package com.wanghai.carwashing.api.interceptor;

import com.wanghai.carwashing.common.helper.JsonHelper;
import com.wanghai.carwashing.common.util.DateUtil;
import com.wanghai.carwashing.core.bean.APICallLog;
import com.wanghai.carwashing.core.bean.config.LogConfig;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * API调用日志拦截器
 * @author 
 */
public class ApiCallLogInterceptor extends HandlerInterceptorAdapter{
    
    public static final String KEY_APICALL_LOG = "apiCallLog";

    /**
     * 创建日志
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception 
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String ip = request.getRemoteAddr();
        APICallLog apiCallLog = new APICallLog();
        apiCallLog.setCreateTime(DateUtil.formatTime(new Date(), null));
        apiCallLog.setIp(ip);
        apiCallLog.setParams(JsonHelper.buildJsonString(request.getParameterMap()));
        apiCallLog.setMethod(request.getMethod());
        apiCallLog.setRequestUri(requestURI);
        request.setAttribute(KEY_APICALL_LOG, apiCallLog);
        
        return super.preHandle(request, response, handler);
    }
    
    /**
     * 返回数据之前调用
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception 
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView); 
    } 
    /* 保存日志
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception 
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        APICallLog apiCallLog =  (APICallLog) request.getAttribute(KEY_APICALL_LOG);
        System.out.println("保存日志:"+JsonHelper.buildJsonString(apiCallLog));
        super.afterCompletion(request, response, handler, ex); 
    }
}
